package com.alkin.thing.utils;

import org.springframework.util.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.List;
import java.util.Set;

public class ValidationUtils {
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> String validateEntity(T obj) {
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        if (set != null && set.size() != 0) {
            StringBuilder sb = new StringBuilder();
            for (ConstraintViolation<T> cv : set) {
                sb.append(cv.getMessage()).append("\r\n");
            }
            return sb.toString();
        }
        return null;
    }

    public static <T> String validateList(List<T> list) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            String msg = validateEntity(list.get(i));
            if (!StringUtils.isEmpty(msg)) {
                sb.append("行").append(i + 1).append(":\r\n").append(msg);
            }
        }
        return sb.toString();
    }

}
